package org.example.studentsystem_back.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.studentsystem_back.common.CommonResponse;
import org.example.studentsystem_back.domain.*;
import org.example.studentsystem_back.dto.PageDTO;
import org.example.studentsystem_back.mapper.*;
import org.example.studentsystem_back.service.CounselorService;
import org.example.studentsystem_back.service.UsersService;
import org.example.studentsystem_back.util.JwtUtil;
import org.example.studentsystem_back.util.RSAUtil;
import org.example.studentsystem_back.vo.dataCenterVo.StudentDataCenterVo.StudentDataCenterVo;
import org.example.studentsystem_back.vo.dataCenterVo.UserDataCenterVo.UserDataCenterVo;
import org.example.studentsystem_back.vo.dataCenterVo.UserDataCenterVo.UserRoleProVo;
import org.example.studentsystem_back.vo.dataCenterVo.UserDataCenterVo.UserSexProVo;
import org.example.studentsystem_back.vo.freshmenMangeVo.FreshmenVo;
import org.example.studentsystem_back.vo.userMangeVo.*;
import org.example.studentsystem_back.vo.userManageVo.PageUserVo;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
* @author 马鑫
* @description 针对表【users】的数据库操作Service实现
* @createDate 2024-07-08 20:11:27
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{
    @Resource
    UsersMapper usersMapper;
    @Resource
    StudentsMapper studentsMapper;
    @Resource
    IdMapper idMapper;
    @Resource
    MenusMapper menusMapper;
    @Resource
    LeadersMapper leadersMapper;
    @Resource
    CounselorMapper counselorMapper;
    @Resource
    FreshmenMapper freshmenMapper;
    /**
     * 注册
     */
    @Override
    public CommonResponse<Users> register(Users users) throws Exception {
//        int count= Math.toIntExact(idMapper.selectCount(null));
//        int x=(int)(Math.random()*count);
//        String id=idMapper.Sselect(x);
//        idMapper.deleteById(id);
//        String resPulic=RSAUtil.getPublicKey();
//        String password= new String(RSAUtil.encrypt(users.getPassword(), resPulic),StandardCharsets.ISO_8859_1);
//        Users users1=new Users();
//        users1.setName(users.getName());
//        users1.setPassword(password);
//        users1.setGender(users.getGender());
//        users1.setUserid(id);
//        users1.setRole(users.getRole());
//        users1.setRsa(resPulic);
//        usersMapper.insert(users1);
//        RSAUtil.pen();
//        return CommonResponse.createForSuccess("注册成功",users1);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",users.getUserid());
        if(usersMapper.selectList(queryWrapper).isEmpty()){
            String rsaPublic=RSAUtil.getPublicKey();
            String password= new String(RSAUtil.encrypt(users.getPassword(), rsaPublic),StandardCharsets.ISO_8859_1);
            RSAUtil.pen();
            users.setPassword(password);
            users.setRsa(rsaPublic);
            usersMapper.insert(users);
            return CommonResponse.createForSuccess("注册成功",users);
        }
        return CommonResponse.createForError("用户名已存在");
//        return CommonResponse.createForSuccess("注册成功",users);
    }

    @Override
    public CommonResponse<UserLoginVo> login(Users users) throws Exception {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("userid",users.getUserid());
        Users users1=usersMapper.selectOne(usersQueryWrapper);
        if(users1!=null){
            String password=users1.getPassword();
            byte[] pwd=password.getBytes(StandardCharsets.ISO_8859_1);
            String password1= RSAUtil.decrypt(pwd,users1.getRsa());
            if(password1.equals(users.getPassword())){
                UserLoginVo userLoginVo=new UserLoginVo();
                UserVo userVo = usersToUserVo(users1);
                users1.setPassword(null);
                userLoginVo.setUserInfo(userVo);
                String token =JwtUtil.createToken(users.getUserid(),users.getPassword());
                userLoginVo.setToken(token);
                QueryWrapper<Menus> queryWrapper=new QueryWrapper<>();
                queryWrapper.like("user_type","%"+users1.getRole()+"%");
                List<Menus> menusList=menusMapper.selectList(queryWrapper);
                userLoginVo.setAppEntryList(menusList);
                return CommonResponse.createForSuccess("登录成功",userLoginVo);
            }
            return CommonResponse.createForError("密码错误");
        }
        return CommonResponse.createForError("账号错误");
    }

    @Override
    public CommonResponse<List<UserVo>> getAllUsers() throws Exception {
        List<Users> usersList = usersMapper.selectList(null);
        List<UserVo> userVoList = new ArrayList<>();
        for(Users user : usersList)
        {
            //解密待实现
            UserVo userVo = usersToUserVo(user);
            userVoList.add(userVo);
        }
        return CommonResponse.createForSuccess("查询成功",userVoList);
    }

    @Override
    public CommonResponse<UserVo> getUserByUserid(String userid) throws Exception {
        Users user = usersMapper.selectById(userid);
        if(user==null)
        {
            return CommonResponse.createForSuccess("没有该userid的用户",null);
        }
        //解密
//        byte[] a= user.getPassword().getBytes(StandardCharsets.ISO_8859_1);
//        System.out.println(Arrays.toString(a));
//        System.out.println(user.getRsa());
//        String p=RSAUtil.decrypt(a,user.getRsa());
//        System.out.println(p);
//        user.setPassword(RSAUtil.decrypt(a,user.getRsa()));
        UserVo userVo = usersToUserVo(user);
        return CommonResponse.createForSuccess("查询成功",userVo);
    }
    @Override
    public CommonResponse<PageUserVo> getUsersByPage(PageDTO pageDto) throws Exception{
        IPage<Users> page = new Page<>(pageDto.getPage(),pageDto.getLimit());
        List<Users> usersList =usersMapper.selectList(page,null);
        Long total = usersMapper.selectCount(null);
        usersList.forEach((user -> user.setPassword(null)));
        PageUserVo pageUserVo = new PageUserVo();
        pageUserVo.setPageList(usersList);
        pageUserVo.setTotal(total);
        return CommonResponse.createForSuccess("查询成功",pageUserVo);
    }

    @Override
    public CommonResponse<UserDataCenterVo> getAllUserDataCenter() {
        List<UserRoleProVo> userRoleProVoList = new ArrayList<>();
        UserDataCenterVo userDataCenterVo = new UserDataCenterVo();
        String roleName = "";
        for(int i =0;i < 5; i++){
            UserRoleProVo userRoleProVo = new UserRoleProVo();
            switch (i){
                case 0:
                    roleName = "管理员";
                    break;
                case 1:
                    roleName = "领导";
                    break;
                case 2:
                    roleName = "辅导员";
                    break;
                case 3:
                    roleName = "学生";
                    break;
                case 4:
                    roleName = "新生";
                    break;
                default:
                    break;
            }
            QueryWrapper<Users> usersRoleQueryWrapper = new QueryWrapper<>();
            usersRoleQueryWrapper.eq("role",i);
            long value = usersMapper.selectCount(usersRoleQueryWrapper);
            userRoleProVo.setName(roleName);
            userRoleProVo.setValue((int) value);
            userRoleProVoList.add(userRoleProVo);
            userDataCenterVo.setRolePro(userRoleProVoList);
        }

        UserSexProVo userSexProVo=new UserSexProVo();
        QueryWrapper<Users> UsersManQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Users> UsersWoManQueryWrapper = new QueryWrapper<>();
        UsersManQueryWrapper.eq("gender","男");
        userSexProVo.setMan(Math.toIntExact(usersMapper.selectCount(UsersManQueryWrapper)));
        UsersWoManQueryWrapper.eq("gender","女");
        userSexProVo.setWoman(Math.toIntExact(usersMapper.selectCount(UsersWoManQueryWrapper)));
        userDataCenterVo.setSexPro(userSexProVo);
        return CommonResponse.createForSuccess("查询成功",userDataCenterVo);
    }


    @Override
    public CommonResponse<UserVo> getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        JwtUtil.verifyToken(token);
        Users user = JwtUtil.getCurrentUser(token);
        UserVo userVo = usersToUserVo(user);
        return CommonResponse.createForSuccess("成功",userVo);
    }

    @Override
    public CommonResponse<UserVo> updateUserInfo(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        Users user = jsonObject.toJavaObject(Users.class);
        if(user.getRole()==0){
            usersMapper.updateById(user);
            UserVo userVo = usersToUserVo(user);
            
            return CommonResponse.createForSuccess("修改成功",userVo);
        }
        else if(user.getRole()==1){
            Leaders leaders = jsonObject.toJavaObject(Leaders.class);
            usersMapper.updateById(user);
            leadersMapper.updateById(leaders);
            UserLeaderVo userLeaderVo = userToULVo(user,leaders);
            
            return CommonResponse.createForSuccess("修改成功",userLeaderVo);
        }
        else if(user.getRole()==2){
            Counselor counselor = jsonObject.toJavaObject(Counselor.class);
            usersMapper.updateById(user);
            counselorMapper.updateById(counselor);
            UserCounselorVo userCounselorVo = userToUCVo(user,counselor);

            return CommonResponse.createForSuccess("修改成功",userCounselorVo);
        }
        else if(user.getRole()==3){
            Students students=jsonObject.toJavaObject(Students.class);
            usersMapper.updateById(user);
            studentsMapper.updateById(students);
            UserStudentVo userStudentVo = userToUSVo(user,students);
            return CommonResponse.createForSuccess("修改成功",userStudentVo);
        }
        else {
            Freshmen freshmen = jsonObject.toJavaObject(Freshmen.class);
            usersMapper.updateById(user);
            freshmenMapper.updateById(freshmen);
            UserFreshmanVo userFreshmanVo = userTOUFVo(user,freshmen);

            return CommonResponse.createForSuccess("修改成功",userFreshmanVo);
        }
    }

    private UserVo usersToUserVo(Users users)
    {
        UserVo userVo = new UserVo();
        userVo.setUserid(users.getUserid());
        userVo.setName(users.getName());
        userVo.setRole(users.getRole());
        userVo.setGender(users.getGender());
        userVo.setPassword(users.getPassword());
        return userVo;
    }


    private UserLeaderVo userToULVo(Users users, Leaders leaders){
        UserLeaderVo userLeaderVo = new UserLeaderVo();
        userLeaderVo.setUserid(users.getUserid());
        userLeaderVo.setName(users.getName());
        userLeaderVo.setPassword(users.getPassword());
        userLeaderVo.setRole(users.getRole());
        userLeaderVo.setGender(users.getGender());

        userLeaderVo.setDepartment(leaders.getDepartment());
        userLeaderVo.setEmployeeId(leaders.getEmployeeId());
        userLeaderVo.setPosition(leaders.getPosition());
        userLeaderVo.setTitle(leaders.getTitle());
        userLeaderVo.setPhone(leaders.getPhone());
        userLeaderVo.setOffice(leaders.getOffice());
        userLeaderVo.setHireDate(leaders.getHireDate());

        return userLeaderVo;
    }

    private UserStudentVo userToUSVo(Users users,Students students){
        UserStudentVo userStudentVo = new UserStudentVo();
        userStudentVo.setUserid(users.getUserid());
        userStudentVo.setName(users.getName());
        userStudentVo.setGender(users.getGender());
        userStudentVo.setRole(users.getRole());
        userStudentVo.setPassword(users.getPassword());

        userStudentVo.setStudentId(students.getStudentId());
        userStudentVo.setClassName(students.getClassName());
        userStudentVo.setMajor(students.getMajor());
        userStudentVo.setDepartment(students.getDepartment());
        userStudentVo.setPhone(students.getPhone());
        userStudentVo.setHukou(students.getHukou());
        userStudentVo.setAddress(students.getAddress());
        userStudentVo.setType(students.getType());
        userStudentVo.setEducation(students.getEducation());
        userStudentVo.setBirthdate(students.getBirthdate());
        userStudentVo.setPoliticalStatus(students.getPoliticalStatus());
        userStudentVo.setNationality(students.getNationality());
        userStudentVo.setEmail(students.getEmail());
        userStudentVo.setIdCard(students.getIdCard());
        userStudentVo.setPassword(users.getPassword());
        userStudentVo.setName(users.getName());
        userStudentVo.setGender(users.getGender());
        userStudentVo.setRole(users.getRole());
        return userStudentVo;
    }

    private UserCounselorVo userToUCVo(Users users,Counselor counselor){
        UserCounselorVo userCounselorVo = new UserCounselorVo();
        userCounselorVo.setUserid(users.getUserid());
        userCounselorVo.setName(users.getName());
        userCounselorVo.setGender(users.getGender());
        userCounselorVo.setRole(users.getRole());
        userCounselorVo.setPassword(users.getPassword());

        userCounselorVo.setEmployeeId(counselor.getEmployeeId());
        userCounselorVo.setClassName(counselor.getClassName());
        userCounselorVo.setDepartment(counselor.getDepartment());
        userCounselorVo.setPhone(counselor.getPhone());
        userCounselorVo.setOfficeAddress(counselor.getOfficeAddress());
        userCounselorVo.setWorkExperience(counselor.getWorkExperience());
        userCounselorVo.setTitle(counselor.getTitle());
        userCounselorVo.setHireDate(counselor.getHireDate());

        return userCounselorVo;
    }

    private UserFreshmanVo userTOUFVo(Users user,Freshmen freshmen  ){
        UserFreshmanVo userFreshmanVo = new UserFreshmanVo();
        userFreshmanVo.setPassword(user.getPassword());
        userFreshmanVo.setName(user.getName());
        userFreshmanVo.setGender(user.getGender());
        userFreshmanVo.setRole(user.getRole());

        userFreshmanVo.setFreshmanId(freshmen.getFreshmanId());
        userFreshmanVo.setUserid(freshmen.getUserid());
        userFreshmanVo.setMajor(freshmen.getMajor());
        userFreshmanVo.setEnrollmentDate(freshmen.getEnrollmentDate());
        userFreshmanVo.setSourceLocation(freshmen.getSourceLocation());
        userFreshmanVo.setPreviousSchool(freshmen.getPreviousSchool());
        userFreshmanVo.setPhone(freshmen.getPhone());
        userFreshmanVo.setEducation(freshmen.getEducation());
        userFreshmanVo.setHasCheckedIn(freshmen.getHasCheckedIn());

        return userFreshmanVo;
    }
}




